﻿using DryIoc;
using HandyControl.Controls;
using log4net;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Client.Extensions;
using PlaceOrder_Shared.Models.Common;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Interop;
using DialogResult = Prism.Services.Dialogs.DialogResult;
using Microsoft.VisualBasic.ApplicationServices;
using System.Windows.Forms;
using DevExpress.Xpo.DB;
using PlaceOrder_Client.Views;
using DevExpress.XtraRichEdit.Model;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System.IO;
using System.Text.Json;
using PlaceOrder_Client.Models.Config;
using Newtonsoft.Json;
using Prism.DryIoc;
using ImTools;
using PlaceOrder_Client.Updater;
using System.Reflection;
using System.Diagnostics;


namespace PlaceOrder_Client.ViewModels
{
    public class LoginViewModel : BindableBase, IDialogAware
    {
        private readonly ILog _log;
        private readonly IUserHelper _userHelper;
        private readonly IData _data;
        private readonly Prism.Services.Dialogs.IDialogService _dialogService;
        public LoginViewModel( IEventAggregator aggregator,ILog log, IUserHelper userHelper,IData data,
            Prism.Services.Dialogs.IDialogService dialogService)
        {
            // 获取用户名设置
            var jsonString = File.ReadAllText("appsettings.json");
            var appSettings = System.Text.Json.JsonSerializer.Deserialize<AppSettings>(jsonString);
            var username = appSettings.Username;
            UserName = username;
            _log = log;
            _userHelper = userHelper;
            _data = data;
            _dialogService = dialogService;
            ExecuteCommand = new DelegateCommand<string>(Execute);
            this.aggregator = aggregator;
        }

        public string Title { get; set; } = "全益下单系统（客户端）";
        public string Icon { get; set; } = "../Images/lily.ico";


        private bool _isLoading=false;
        public bool IsLoading
        {
            get { return _isLoading; }
            set
            {
                if (_isLoading != value)
                {
                    _isLoading = value;
                    RaisePropertyChanged();
                }
            }
        }

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            LoginOut();
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
        }

        #region Login

        private int selectIndex;

        public int SelectIndex
        {
            get { return selectIndex; }
            set { selectIndex = value; RaisePropertyChanged(); }
        }


        public DelegateCommand<string> ExecuteCommand { get; private set; }


        private string userName;

        public string UserName
        {
            get { return userName; }
            set { userName = value; RaisePropertyChanged(); }
        }
        public string PassWord
        {
            get { return passWord; }
            set { passWord = value; RaisePropertyChanged(); }
        }
        private string passWord;

        private readonly IEventAggregator aggregator;

        

        private void Execute(string obj)
        {
            switch (obj)
            {
                case "Login": Login(); break;
                case "Cancel": LoginOut(); break;
                case "ResgiterPage": SelectIndex = 1; break;
                case "Return": SelectIndex = 0; break;
            }
        }

        public static Stopwatch Stopwatch { get; private set; }
        async void Login()
        {
            IsLoading = true;
            string NickName = null;
            //ShowOrderView();
            //return;
            if (string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(PassWord))
            {
                Growl.Info("请输入用户名/密码", "LoginMsg");
                IsLoading = false; // 设置加载状态为 false
                return;
            }

            UserInfo userInfo = new UserInfo();
            userInfo.userName = UserName;
            userInfo.password = PassWord;

            try
            {
                var loginResult = await _userHelper.Login(userInfo);


                if (loginResult.Item2)
                {
                    //if (UserHelper.UserName != "admin")
                    //{
                    //    Growl.Info("请使用admin登录账户", "LoginMsg");
                    //    return;
                    //}

                    //Stopwatch = new Stopwatch();
                    //Stopwatch.Start();
                }
                else
                {
                    Growl.Error(loginResult.Item1, "LoginMsg");
                }

                string logMsg = null;
                if (loginResult.Item1 != null && loginResult.Item2 == true)
                {

                    var temp = await UserHelper.GetAllUserInfo();
                    IsLoading = false; // 设置加载状态为 false
                    LilyUserInfo myUserInfo = temp.Where(o => o.UserName == UserName).FirstOrDefault();
                    if (myUserInfo != null)
                    {
                        UserHelper.UserID = myUserInfo.UserId;
                        UserHelper.NickName = myUserInfo.NickName;

                    }
                    else
                    {
                        HandyControl.Controls.MessageBox.Show("查无此ID号");
                        PrismApplication.Current.Dispatcher.Invoke(() =>
                        {
                            PrismApplication.Current.Shutdown(); // 正确的关闭应用程序方法
                        });
                    }



                    logMsg = "登录成功." + GetGreeting() + NickName + "~";
                    //if (DailyData.NewClientVersion != ProgramUpdater.CurrentVersion)
                    //{
                    //    ProgramUpdater.CheckUpdate(DailyData.NewClientVersion);
                    //    return;
                    //}


                    var appSettings = new AppSettings
                    {
                        Username = this.UserName
                    };

                    // 将修改后的对象转换为 JSON 字符串
                    var updatedJsonString = System.Text.Json.JsonSerializer.Serialize(appSettings);

                    // 写入 JSON 文件
                    File.WriteAllText("appsettings.json", updatedJsonString);
                    aggregator.SendMessage(logMsg);
                    AppLog.WriteInfo(logMsg);
                    //ShowOrderView();
                    RequestClose?.Invoke(new DialogResult(ButtonResult.OK));

                    Growl.InfoGlobal($"{logMsg}");

                }
                else
                {
                    logMsg = "登录失败." + GetGreeting() + NickName + "~";
                    AppLog.WriteError(logMsg);
                    aggregator.SendMessage(loginResult.Item1, "Login");
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("登录异常" + ex.Message);
            }
            finally
            {
                IsLoading = false;
            }
           

            //await Task.Delay(100);
            //// 停止计时并记录总时间
            //Stopwatch.Stop();
            //var elapsedTime = Stopwatch.Elapsed;
            //Growl.InfoGlobal($"总共花费时间: {elapsedTime.TotalSeconds} 秒");
            //AppLog.WriteInfo($"总共花费时间: {elapsedTime.TotalSeconds} 秒");



        }

        private string GetGreeting()
        {
            var hour = DateTime.Now.Hour;
            if (hour >= 6 && hour < 12)
            {
                return "早上好，";
            }
            else if (hour >= 12 && hour < 18)
            {
                return "中午好，";
            }
            else
            {
                return "晚上好，";
            }
        }

        //private async void  ShowOrderView()
        //{


        //    for (int i = 0; i < 3; i++) // 创建3个窗口
        //    {
        //        var orderWindow = new OrderView
        //        {
        //            Title = $"{UserHelper.NickName}+下单窗口{i + 1}",
        //            Left = 111 + i * 20, // 设置窗口左侧位置
        //            Top = 222 + i * 20  // 设置窗口顶部位置
        //        };
        //        await Task.Delay(50); // 添加延迟，避免短时间内同时显示多个窗口
        //        orderWindow.Show();
        //    }
        //}
        public static WindowConfig config;

        public async static void ShowOrderView()
        {
            try
            {
                string filePath = "PlaceOrderViewConfig.json";
                if (File.Exists(filePath))
                {
                    string json = await File.ReadAllTextAsync(filePath);

                    config = JsonConvert.DeserializeObject<WindowConfig>(json);
                    if (config == null || config.WindowPositions == null) return;

                    var orderViews = config.WindowPositions.ContainsKey("OrderView") ? config.WindowPositions["OrderView"] : new List<WindowPosition>();
                    var longHuView = config.WindowPositions.ContainsKey("LongHuView") ? config.WindowPositions["LongHuView"] : new List<WindowPosition>();
                    var onHoldView = config.WindowPositions.ContainsKey("OnHoldView") ? config.WindowPositions["OnHoldView"] : new List<WindowPosition>();
                    var messageView = config.WindowPositions.ContainsKey("ChatMessageView") ? config.WindowPositions["ChatMessageView"] : new List<WindowPosition>();

                    // 使用并行任务处理多个窗口的初始化和显示
                    var tasks = new List<Task>();

                    // 在UI线程上创建并显示窗口
                    await PrismApplication.Current.Dispatcher.InvokeAsync(async () =>
                    {
                        for (int i = 0; i < orderViews.Count; i++)
                        {
                            var orderView = orderViews[i];
                            var orderWindow = new OrderView
                            {
                                Title = $"{UserHelper.NickName}{i + 1}",
                                Left = orderView.Left,
                                Top = orderView.Top,
                                Width = orderView.Width,
                                Height = orderView.Height,
                            };
                            if (!OrderListViewModel.CheckIfInWhiteList(orderView.TsCode))
                            {
                                Growl.WarningGlobal($"收藏的{orderView.TsCode}不在券码白名单中，请检查！");
                                continue;
                            }

                            if (orderView.IsFavourite)
                            {
                                orderWindow.Show();
                                //orderWindow._vm.CbDays = $"System.Windows.Controls.ComboBoxItem: Tick图-{orderView.CbDays.ToString()}天";

                                if(orderWindow._vm == null)
                                {
                                    return;
                                }
                                orderWindow._vm.CbDays = $"Tick图-{orderView.CbDays}天";

                                orderWindow._vm.IsFavourite = true;

                                orderWindow._vm.BondNumber = orderView.TsCode;


                                await orderWindow._vm.OnTsSelectionChangedAsync(orderView.TsCode);

                                if (orderWindow._vm != null)
                                {
                                    orderWindow._vm.ChangeCbDays();
                                }
                            }
                            await Task.Delay(0); // 添加延迟，避免短时间内同时显示多个窗口
                        }
                    });

                    if (longHuView.Count > 0)
                    {
                        tasks.Add(MainViewModel.CreateLongHuViewAsync(longHuView[0]));
                    }else
                    {
                        tasks.Add(MainViewModel.CreateLongHuViewAsync());
                    }

                    if (onHoldView.Count > 0 )
                    {
                        tasks.Add(MainViewModel.CreateOnHoldViewAsync(onHoldView[0]));
                    }

                    if (messageView.Count > 0)
                    {
                        tasks.Add(MainViewModel.ChatMessageViewAsync(messageView[0]));
                    }else
                    {
                        tasks.Add(MainViewModel.ChatMessageViewAsync());

                    }

                    // 等待所有任务完成
                    await Task.WhenAll(tasks);
                }
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Show("加载窗口位置配置失败：" + ex.Message);
            }
        }


        //private async void ShowOrderView()
        //{
        //    try
        //    {
        //        string filePath = "PlaceOrderViewConfig.json";
        //        if (File.Exists(filePath))
        //        {
        //            string json = File.ReadAllText(filePath);

        //            var config = JsonConvert.DeserializeObject<WindowConfig>(json);
        //            List<WindowPosition> orderViews = null;
        //            List<WindowPosition> longHuView = null;
        //            List<WindowPosition> mainView = null;
        //            List<WindowPosition> onHoldView = null;
        //            List<WindowPosition> messageView = new List<WindowPosition>();
        //            if (config == null || config.WindowPositions == null) { return; }
        //            if (config != null && config.WindowPositions != null)
        //            {
        //                // 如果config为空或者不包含WindowPositions键，初始化一个空的windowPositions列表
        //                // 获取 OrderView 的位置信息
        //                orderViews = config.WindowPositions.ContainsKey("OrderView") ? config.WindowPositions["OrderView"] : new List<WindowPosition>();
        //                longHuView = config.WindowPositions.ContainsKey("LongHuView") ? config.WindowPositions["LongHuView"] : new List<WindowPosition>();
        //                onHoldView = config.WindowPositions.ContainsKey("OnHoldView") ? config.WindowPositions["OnHoldView"] : new List<WindowPosition>();

        //                messageView = config.WindowPositions.ContainsKey("ChatMessageView") ? config.WindowPositions["ChatMessageView"] : new List<WindowPosition>();

        //            }

        //            for (int i = 0; i < orderViews.Count; i++)
        //            {
        //                var orderWindow = new OrderView
        //                {
        //                    Title = $"{UserHelper.NickName} 下单窗口{i + 1}",
        //                    Left = orderViews[i].Left,
        //                    Top = orderViews[i].Top,
        //                    Width = orderViews[i].Width,
        //                    Height = orderViews[i].Height,
        //                };
        //                // 使用Dispatcher来确保在UI线程上显示窗口
        //                await PrismApplication.Current.Dispatcher.InvokeAsync(() =>
        //                {
        //                    orderWindow.Show();
        //                });

        //                await Task.Delay(50); // 添加延迟，避免短时间内同时显示多个窗口
        //            }

        //            if(longHuView!=null&&longHuView.Count>0)
        //            {
        //                MainViewModel.CreateLongHuViewAsync(longHuView[0]);
        //            }

        //            if (onHoldView != null && onHoldView.Count > 0)
        //            {
        //                MainViewModel.CreateOnHoldViewAsync(onHoldView[0]);
        //            }

        //            if (messageView != null && messageView.Count > 0)
        //            {
        //                MainViewModel.ChatMessageViewAsync(messageView[0]);
        //                //MainViewModel.CreateOnHoldViewAsync(onHoldView[0]);
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        HandyControl.Controls.MessageBox.Show("加载窗口位置配置失败：" + ex.Message);
        //    }

        //}

        //private async void ShowOrderWindows(object? obj)
        //{
        //    //Parallel.ForEach(obj =>
        //    //{

        //    //});
        //    for (int i = 0; i < 3; i++) // 创建3个窗口
        //    {
        //        var orderWindow = new OrderView
        //        {
        //            Title = $"{UserHelper.NickName}+下单窗口{i + 1}",
        //            Left = 111 + i * 20, // 设置窗口左侧位置
        //            Top = 222 + i * 20  // 设置窗口顶部位置
        //        };
        //        await Task.Delay(100); // 添加延迟，避免短时间内同时显示多个窗口
        //        orderWindow.Show();
        //    }
        //}

        void LoginOut()
        {
            //IsLoading = !IsLoading;
            RequestClose?.Invoke(new DialogResult(ButtonResult.No));

        }

        #endregion
    }

    public class UserData
    {
        [JsonProperty("searchValue")]
        public object SearchValue { get; set; }

        [JsonProperty("createBy")]
        public string CreateBy { get; set; }

        [JsonProperty("createTime")]
        public string CreateTime { get; set; }

        [JsonProperty("updateBy")]
        public object UpdateBy { get; set; }

        [JsonProperty("updateTime")]
        public object UpdateTime { get; set; }

        [JsonProperty("remark")]
        public object Remark { get; set; }

        [JsonProperty("params")]
        public Dictionary<string, object> Params { get; set; }

        [JsonProperty("userType")]
        public object UserType { get; set; }

        [JsonProperty("userId")]
        public int UserId { get; set; }

        [JsonProperty("deptId")]
        public object DeptId { get; set; }

        [JsonProperty("userName")]
        public string UserName { get; set; }

        [JsonProperty("nickName")]
        public string NickName { get; set; }

        [JsonProperty("email")]
        public object Email { get; set; }

        [JsonProperty("phonenumber")]
        public string Phonenumber { get; set; }

        [JsonProperty("sex")]
        public object Sex { get; set; }

        [JsonProperty("avatar")]
        public object Avatar { get; set; }

        [JsonProperty("salt")]
        public object Salt { get; set; }

        [JsonProperty("status")]
        public string Status { get; set; }

        [JsonProperty("delFlag")]
        public string DelFlag { get; set; }

        [JsonProperty("loginIp")]
        public object LoginIp { get; set; }

        [JsonProperty("loginDate")]
        public object LoginDate { get; set; }

        [JsonProperty("hwinfo")]
        public string Hwinfo { get; set; }

        [JsonProperty("roles")]
        public List<Role> Roles { get; set; }

        [JsonProperty("roleIds")]
        public object RoleIds { get; set; }

        [JsonProperty("postIds")]
        public object PostIds { get; set; }

        [JsonProperty("admin")]
        public bool Admin { get; set; }
    }

    public class Role
    {
        [JsonProperty("searchValue")]
        public object SearchValue { get; set; }

        [JsonProperty("createBy")]
        public object CreateBy { get; set; }

        [JsonProperty("createTime")]
        public object CreateTime { get; set; }

        [JsonProperty("updateBy")]
        public object UpdateBy { get; set; }

        [JsonProperty("updateTime")]
        public object UpdateTime { get; set; }

        [JsonProperty("remark")]
        public object Remark { get; set; }

        [JsonProperty("params")]
        public Dictionary<string, object> Params { get; set; }

        [JsonProperty("roleId")]
        public int RoleId { get; set; }

        [JsonProperty("roleName")]
        public string RoleName { get; set; }

        [JsonProperty("roleKey")]
        public string RoleKey { get; set; }

        [JsonProperty("roleSort")]
        public string RoleSort { get; set; }

        [JsonProperty("dataScope")]
        public string DataScope { get; set; }

        [JsonProperty("menuCheckStrictly")]
        public bool MenuCheckStrictly { get; set; }

        [JsonProperty("deptCheckStrictly")]
        public bool DeptCheckStrictly { get; set; }

        [JsonProperty("status")]
        public string Status { get; set; }

        [JsonProperty("delFlag")]
        public object DelFlag { get; set; }

        [JsonProperty("flag")]
        public bool Flag { get; set; }

        [JsonProperty("menuIds")]
        public object MenuIds { get; set; }

        [JsonProperty("deptIds")]
        public object DeptIds { get; set; }

        [JsonProperty("admin")]
        public bool Admin { get; set; }
    }
}
